# -*- coding: utf-8 -*-

from flask import request, abort, url_for
from google.appengine.ext import db
from dicthash.utils import project2dict
from dicthash.decorators import html_it, json_it, glue_GET_POST

from ..backends.working.models import Lenta, Tag, DuplicateTagError
from ..forms import TagForm
from .lenta import _fetch_lenta, _lenta_key

__all__ = ['add_tag', 'view_tag', 'edit_tag', 'delete_tag']


TagProperties = ['name', 'namespace', 'lenta_id', 'counter']

def _fetch_tag(tag_name, lenta_id, namespace=None):
    """ """
    parent_key = db.Key.from_path('Lenta', lenta_id, namespace=namespace)
    key = db.Key.from_path('Tag', tag_name, parent=parent_key, namespace=namespace)
    return Tag.get(key) or abort(404)

def _proj_t(tag):
    """ """
    return project2dict(tag, TagProperties)


def _add_tag_GET(lenta_id):
    """ """
    _fetch_lenta(lenta_id)
    return {}

def _add_tag_POST(lenta_id):
    """
    Add new `Tag` entity.
    """
    _fetch_lenta(lenta_id)
    
    form = TagForm(request.form)
    if form.is_valid():
        tag = Tag.new(form.cleaned_data['name'], parent=db.Key.from_path('Lenta', lenta_id))
        try:
            tag.put()
        except DuplicateTagError, e:
            abort(409, e.message)    
        return dict(tag=_proj_t(tag), lenta_id=lenta_id)
    else:
        return dict(errors=form.errors, tag=request.form)
    
add_tag = html_it ('/lenta/tag/add_tag.html', '/lenta/tag/add_tag_ok.html') \
                                (glue_GET_POST(_add_tag_GET, _add_tag_POST))


def _view_tag(tag_name, lenta_id, namespace):
    """
    Get `Tag` entity from datastore.
    """
    return dict(tag=_proj_t(_fetch_tag(tag_name, lenta_id, namespace))) 

view_tag = html_it ('/lenta/tag/view_tag.html') (_view_tag)
view_tag_json = json_it () (_view_tag)


def _edit_tag_GET(tag_name, lenta_id):
    """ """
    return dict(tag=_proj_t(_fetch_tag(tag_name, lenta_id)))

def _edit_tag_POST(tag_name, lenta_id):
    """ """
    tag = _fetch_tag(tag_name, lenta_id)
        
    form = TagForm(request.form)
    if form.is_valid():
        tag = tag.update(form.cleaned_data['name'])
        return dict(tag=_proj_t(tag))
    else:
        return dict(errors=form.errors, tag=request.form)
    
edit_tag = html_it ('/lenta/tag/edit_tag.html', '/lenta/tag/edit_tag_ok.html') \
                                (glue_GET_POST(_edit_tag_GET, _edit_tag_POST))


def _delete_tag_GET(tag_name, lenta_id):
    """ """
    return dict(tag=_proj_t(_fetch_tag(tag_name, lenta_id)))

def _delete_tag_POST(tag_name, lenta_id):
    """ """
    tag = _fetch_tag(tag_name, lenta_id)
    tag.delete()
    return dict()

delete_tag = html_it ('/lenta/tag/delete_tag.html', '/lenta/tag/delete_tag_ok.html') \
                                (glue_GET_POST(_delete_tag_GET, _delete_tag_POST))
                                
                                
def _view_all_tags_for_lenta(lenta_id, namespace):
    """
    Get `Tag` entities for a given `Lenta`.
    """
    query = Tag.all(namespace=namespace).ancestor(_lenta_key(lenta_id, namespace))
    
    return dict(tags=[_proj_t(tag) for tag in query])

view_all_tags_for_lenta = html_it ('/lenta/tag/view_all_tags_for_lenta.html') (_view_all_tags_for_lenta)
view_all_tags_for_lenta_json = json_it () (_view_tag)